package com.mario.web;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.bind.annotation.Command;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.mario.domain.Product;
import com.mario.service.ProductManager;
import com.mario.util.WebConstants;

@Controller
@Scope("prototype")
public class ProductDialogController extends GenericForwardComposer<Window> {

	private static final long serialVersionUID = 2527514225021137567L;
	protected final static Logger logger = Logger.getLogger(ProductDialogController.class);
	
	//***************************************************************
	// Attributes
	//***************************************************************
	
	@Autowired
	private ProductManager productManager;
	
	@Wire private Textbox descriptionTextbox;
	@Wire private Textbox priceTextbox;
	
	private Product product;
	private Window window;
	private Window parentWindow;
	
	//***************************************************************
	// Methods
	//***************************************************************
	
	@Override
	public void doAfterCompose(Window window) throws Exception {
		logger.info("BEGIN Do After compose ");
		super.doAfterCompose(window);
		
		this.window = window;
		
		// getting parameters
		parentWindow = (Window) arg.get(WebConstants.PARENT_WINDOW);
		product = (Product) arg.get(WebConstants.SELECTED);
		
		if (product != null) {
			descriptionTextbox.setValue(product.getDescription());
			priceTextbox.setValue(product.getPrice().toString());
		}
		
		logger.info("END Do After compose ");
	}
	
	@Command
	public void onClick$save(){
		logger.info("BEGIN saving Product.");
		
		String description = descriptionTextbox.getValue();
		Double price = Double.valueOf(priceTextbox.getValue());
		
		if (product != null) {
			product.setDescription(description);
			product.setPrice(price);
			productManager.updateProduct(product);
		} else {
			productManager.addProduct(description, price);
		}

		closeModalWindow();
	}

	@Command
	public void onClick$cancel(){
		closeModalWindow();
	}
	
	private void closeModalWindow() {
		logger.info("Closing Window.");		
		Events.sendEvent(new Event("onProductSaved", parentWindow));
		this.window.detach();
	}
	
}
